﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Zgq.CommonTools
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="MothedName"></param>
    /// <param name="_objectPara"></param>
    public delegate void ThreadMethodDelegate(string MothedName, object _objectPara);
    /// <summary>
    /// 
    /// </summary>
    public   class ThreadPoolWait
    {
         private    List<ManualResetEvent> manualEvents = new List<ManualResetEvent>();
        /// <summary>
        /// 
        /// </summary>
         public event ThreadMethodDelegate ThreadMethodEvent;



        /// <summary>
        /// 增加子线程需要执行的方法名称
        /// </summary>
        /// <param name="MothedName">方法名称</param>
        public void AddMothed(string MothedName)
        {
            AddMothed( MothedName, null );
        }
        /// <summary>
        /// 增加子线程需要执行的方法名称及参数
        /// </summary>
        /// <param name="MothedName">方法名称</param>
        /// <param name="_objectPara">方法参数</param>
        public  void AddMothed(string MothedName,object  _objectPara ) 
         {
            ManualResetEvent mre = new ManualResetEvent(false);
            manualEvents.Add(mre);
            ThreadWaitPara para = new ThreadWaitPara();
            para.Mre = mre;
            para.MothedName = MothedName;
            para.MothedNameParas = _objectPara;
            ThreadPool.QueueUserWorkItem(ThreadMethod, para);
        }
        /// <summary>
        /// 主线程等待，子线程全部执行结束后，再执行下面逻辑
        /// </summary>
        public void WaitAll()
        {
            WaitHandle.WaitAll(manualEvents.ToArray());
        }

        private void ThreadMethod(object _OBJECT)
        {
            ThreadWaitPara para = _OBJECT as ThreadWaitPara;
            try
            {
              if (ThreadMethodEvent !=null )
                {
                    ThreadMethodEvent(para.MothedName,para.MothedNameParas);  
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                para.Mre.Set();
            }
        }


    }



    /// <summary>
    /// 多线程等待类 使用
    /// </summary>
     class ThreadWaitPara
    {
        public string MothedName;
        public object MothedNameParas;
        public ManualResetEvent Mre;
    }
}
